package cn.itsource.pethome.user.controller;

import cn.itsource.pethome.basic.util.RedisUtils;
import cn.itsource.pethome.user.domain.User;
import cn.itsource.pethome.user.domain.dto.UserDto;
import cn.itsource.pethome.user.service.IUserService;
import cn.itsource.pethome.basic.util.AjaxResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @description: 描述:
 * @date: 2020/8/14 16:22
 * @author: summer
 * version: 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 功能描述: 注册时 电话号码验证
     * @param phone 电话号码
     * @return: cn.itsource.pethome.basic.util.AjaxResult
     * @Date: 2020/8/16
     */
    @PostMapping("/loadPhone")
    public AjaxResult loadPhone(@RequestBody Map<String,String> phone){
        String number = phone.get("phone");
        return userService.loadPhone(number);
    }

    /**
     * 功能描述: 用户注册
     * @param userDto 前端页面注册信息 临时对象
     * @return: cn.itsource.pethome.basic.util.AjaxResult
     * @Date: 2020/8/16
     */
    @PutMapping("/register")
    public AjaxResult register(@RequestBody UserDto userDto){
        try {
            userService.register(userDto);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, e.getMessage());
        }
    }

    @RequestMapping("/loadEmail")
    public AjaxResult loadEmail(@RequestBody Map<String,String> partm){
        String email = partm.get("email");
        return userService.loadEmail(email);
    }

    /**
     * 功能描述: 登录
     * @param user 封装了：用户名 密码
     * @return: cn.itsource.pethome.basic.util.AjaxResult
     * @Date: 2020/8/16
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody User user){
        try {
            User loginUser = userService.getUsernameAndPassword(user.getUsername(), user.getPassword());
            //把对象转为json字符串
            String jsonString = JSON.toJSONString(loginUser);
            //令牌
            String token = UUID.randomUUID().toString();
            //把登录用户存储到redis中，有效期是30分钟
            RedisUtils.INSTANCE.set(token,jsonString ,60*60*24 );
            //把token和登录用户封装到map集合中
            Map<Object, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("loginUser", loginUser);
            return new AjaxResult().setResult(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, e.getMessage());
        }
    }

}
